package com.gopay.bis.citic.ebank.operation;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.citic.ebank.pay.CiticB2bMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.ICertHelper;
import com.lsy.baselib.crypto.processor.ECCryptoProcessor;

/**
 * @CiticB2bCertHelper.java
 * @author wanggang
 * @2013-12-4 下午2:02:03  www.gopay.com.cn Inc.All rights reserved.
 */
public class CiticB2bCertHelper implements ICertHelper{
	
	@Override
	public String sign(BaseMessage baseMessage) throws GopayException {
		try {
			CiticB2bMessage message = (CiticB2bMessage) baseMessage;
			String signMessage = "";
			ECCryptoProcessor processor = new ECCryptoProcessor();
			String certContent = readFile(message.getPrivateKeyPath());
			String keyContent = readFile(message.getPrivateKeyPath2nd());
			processor.setSignerCertificate(certContent.getBytes());
			processor.setSignerPrivatekey(keyContent.getBytes(), message.getPrivatePwd());
			BankLogUtils.printB2BSignPlainLog(baseMessage);
			byte[] signedMessage = processor.sign(message.getPlainMessage().getBytes());
			signMessage = new String(signedMessage);
			BankLogUtils.printB2BSignSignatureLog(baseMessage, signMessage);
			return signMessage;
		} catch (Exception e) {
			BankLogUtils.printB2BSignExceptionLog(baseMessage, e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6028);
		}
	}

	@Override
	public Object verify(BaseMessage baseMessage) throws GopayException {
		try {
			CiticB2bMessage message = (CiticB2bMessage) baseMessage;
			String plainMessage = "";
			String citicPublic = "";
			citicPublic = readFile(message.getPublicKeyPath());
			ECCryptoProcessor processor = new ECCryptoProcessor();
			processor.addTrustedCertificate(citicPublic.getBytes());
			BankLogUtils.printB2BVerifyPlainLog(baseMessage);
			BankLogUtils.printB2BVerifySignatureLog(baseMessage);
			processor.verify(message.getSignMessage().getBytes());
			plainMessage = new String(processor.getOrderMessage(message.getSignMessage().getBytes()));
			BankLogUtils.printB2BVerifyResultLog(baseMessage, true);
			return plainMessage;
		} catch (Exception e) {
			BankLogUtils.printB2BVerifyExceptionLog(baseMessage, e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6030);
		}
	}

	/**
	 * 通过路径读取证书文件内容.
	 * 
	 * @param path
	 * @return
	 * @throws IOException
	 */
	private String readFile(String path) throws IOException {
		FileReader fr = new FileReader(path);
		BufferedReader br = new BufferedReader(fr);
		StringBuffer sb = new StringBuffer();
		while (br.ready()) {
			sb.append(br.readLine());
		}
		if (null != fr) {
			fr.close();
		}
		if (null != br) {
			br.close();
		}
		return sb.toString();
	}

}
